# http://127.0.0.1:18080/s_server/moni/?code=300684&start_day=200&all_money=10000&times_percent=1
# coding: utf-8
import json
import requests
from requests.adapters import HTTPAdapter
import urllib3
import torch
from s_server.deeplearning.predict import Predict
import os

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

def pretty_print_json(data):
    """Pretty prints JSON data"""
    # parsed_data = json.loads(data)
    pretty_data = json.dumps(data, indent=4, sort_keys=True)
    print(pretty_data)


class S_Client(object):
    def __init__(self):
        self.timeout = 8640000
        self.s = requests.Session()
        self.s.mount("http://", HTTPAdapter(max_retries=3))
        self.s.mount("https://", HTTPAdapter(max_retries=3))

        self.s_get_codes_url = 'http://127.0.0.1:18080/s_server/get_code_infos/'
        self.s_codes_url = 'http://127.0.0.1:18080/s_server/codes/'
        self.s_moni_url = 'http://127.0.0.1:18080/s_server/moni/'
        self.s_get_all_datas_url = 'http://127.0.0.1:18080/s_server/get_stp_infos/'
        self.has_last_url = "http://127.0.0.1:18080/s_server/code_data_exist_and_has_last/"
        self.moni_custom_days_urls = "http://127.0.0.1:18080/s_server/moni_custom_days/"
        self.get_moni_days_url = "http://127.0.0.1:18080/s_server/get_st_days_for_moni/"
        self.moni_custom_days_not_write_urls = "http://127.0.0.1:18080/s_server/moni_custom_days_not_write/"
        self.headers = {"content-type": "application/json"}
        self.Predict =  Predict()

    def do_moni(self):
        res = self.s.get(
            self.s_codes_url,
            headers=self.headers,
            timeout=self.timeout
        )
        codes = res.json()
        for code in codes:
            # print(code)
            # if code["dm"] != "000007":
            #     continue
            # 模拟时间的天数为moni_compute_days的第一项和moni_day_size的总和
            # moni_compute_days = "17,13,11,7,5,3,2,1"
            # moni_compute_days = "60,30,15,10,5,3"
            moni_compute_days = "30,20,15,10,5,3,2"
            # moni_compute_days = "10,5,3,2"
            moni_day_size = 30
            random = 1
            random_size = 500
            predict_day_size = 10
            his_day_size = int(moni_compute_days.split(",")[0])
            moni_days_for_code = self.get_moni_days_by_code(code["dm"], his_day_size, moni_day_size, predict_day_size,
                                                            random,
                                                            random_size)
            print("扫描信息", moni_days_for_code)

            # print(moni_days_for_code)
            if moni_days_for_code["day_list"]:
                # print(moni_days_for_code)
                moni_days_for_code.update({
                    "moni_compute_days": moni_compute_days,
                    "all_money": 10000,
                    "times_percent": 1.0,
                    "at": 1.00,
                    "bt": 1.00
                })
                res = self.s.post(
                    self.moni_custom_days_urls,
                    data=json.dumps(moni_days_for_code),
                    headers=self.headers,
                    timeout=self.timeout
                )
                # print(res.json())
                # for i in res.json():
                #     print(i["last_money"],i["label"])
                success_num = 0
                faile_num = 0

                for i in res.json():
                    # print(i)
                    if i["label"] == 1:
                        success_num += 1
                    else:
                        faile_num += 1
                print("准确率 ", success_num / (success_num + faile_num))

            # else:
            #     print(code["dm"],"数据不足")

    def get_moni_days_by_code(self, code, his_day_size, moni_day_size, predict_day_size, random, random_size):
        "?code=300686&his_day_size=120&moni_day_size=60&predict_day_size=20&random=1&random_size=300"
        res = self.s.get(
            self.get_moni_days_url + "?code={}&his_day_size={}&moni_day_size={}&predict_day_size={}&random={}&random_size={}".format(
                code, his_day_size, moni_day_size, predict_day_size, random, random_size
            ),
            headers=self.headers,
            timeout=self.timeout
        )
        return res.json()

    def get_get_codes(self):
        res = self.s.get(
            self.s_get_codes_url,
            headers=self.headers,
            timeout=self.timeout
        )
        print(res.json())

    def get_all_datas(self):
        res = self.s.get(
            self.s_get_all_datas_url,
            headers=self.headers,
            timeout=self.timeout
        )
        # print(res.json())

    def get_moni_data(self):
        res = self.s.get(
            self.s_codes_url,
            headers=self.headers,
            timeout=self.timeout
        )
        codes = res.json()
        for code in codes:
            try:
                # print(code["dm"])
                url = self.has_last_url + "?code={}".format(code["dm"])
                res = self.s.get(
                    url,
                    headers=self.headers,
                    timeout=self.timeout
                )
                if res.status_code == 200:
                    url = self.s_moni_url + "?code={}&start_day=120&all_money=10000&times_percent=1.0&at=1.0&bt=1.0".format(
                        code["dm"])
                    res = self.s.get(
                        url,
                        headers=self.headers,
                        timeout=self.timeout
                    )
                    res_json = res.json()
                    if res_json["last_money"] != 10000:
                        print(code["dm"], res_json)
            except Exception:
                print(code["dm"], "error")

    def do_moni_compute(self):
        code = "000007"
        moni_compute_days = "30,20,15,10,5,3,2"
        moni_day_size = 30
        random = 1
        random_size = 1
        predict_day_size = 10
        his_day_size = int(moni_compute_days.split(",")[0])
        moni_days_for_code = self.get_moni_days_by_code(code, his_day_size, moni_day_size, predict_day_size, random,
                                                        random_size)

        print(moni_days_for_code)
        if moni_days_for_code["day_list"]:
            # print(moni_days_for_code)
            moni_days_for_code.update({
                "moni_compute_days": moni_compute_days,
                "all_money": 10000,
                "times_percent": 1.0,
                "at": 1.00,
                "bt": 1.00
            })
            res = self.s.post(
                self.moni_custom_days_not_write_urls,
                data=json.dumps(moni_days_for_code),
                headers=self.headers,
                timeout=self.timeout
            )
            # pretty_print_json(res.json())
            print(res.json()[0]["code"])
            print(res.json()[0]["moni_days"][-1])
            last_data = float(res.json()[0]["could_moni_data"]["c"])
            max_data = max([float(i["c"]) for i in res.json()[0]["cloud_predict_data"]])
            print(last_data)
            print(max_data)
            print((max_data - last_data) / last_data)
            label = res.json()[0]["label"]
            # model = model.to(device)
            # model.eval()
            # test_input = torch.stack([i[0] for i in test_dataset])
            # print(test_input.shape)
            s1 = torch.FloatTensor([float(i) for i in res.json()[0]["last_zd_list"]])
            s2 = torch.FloatTensor([float(i) for i in res.json()[0]["last_state_list"]])
            # print("res.json()",len(res.json()[0]["last_zd_list"]))
            # print("res.json()",len(res.json()[0]["last_state_list"]))
            test_input = torch.stack([s1, s2]).unsqueeze(0)
            # print(test_input.shape)
            test_out_put = self.Predict.predict_data(test_input)
            # print(label)
            result = float(test_out_put.item())
            return label, 1 if result > 0.5 else 0

        # else:
        #     print(code["dm"],"数据不足")


client = S_Client()
print("开始执行接口")
true_size = 0
moni_size = 20
for i in range(moni_size):
    label, res = client.do_moni_compute()
    print(label, res)
    if int(true_size) == int(res):
        true_size += 1

print("正确率", true_size / float(moni_size))
